package com.lant.aspect;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lant.enums.ResponseStatusEnum;
import com.lant.pojo.LantResult;
import com.lant.pojo.LantUser;
import com.lant.service.LantUserService;
import com.lant.utils.CookieUtils;
import com.lant.utils.ObjectUtils;
import com.lant.utils.StringUtils;
import com.lant.web.common.content.LantUserLocal;
import com.lant.web.constant.FieldConstant;

@Aspect
@Component
public class ContextAspect {
    @Resource
    private HttpServletRequest servletRequest;
    @Autowired
    private LantUserService lantUserService;

    private static final Logger logger = LoggerFactory.getLogger(ContextAspect.class);

    /**
     * 环绕通知
     */
    @Around("execution(* com.lant.web.controller..*.*(..))")
    public Object proceed(ProceedingJoinPoint pjp) throws Throwable {
        Object result = StringUtils.EMPTY;

        LantUser lantUser = null;
        String userName = StringUtils.EMPTY;
        try {
            // 初始化
            lantUser = initUserContext();
            result = pjp.proceed();
            userName = lantUser == null ? StringUtils.EMPTY : lantUser.getName();
        } catch (Throwable throwable) {
            logger.error("name:{}, url:{}", userName, servletRequest.getRequestURL(), throwable);
            throw throwable;
        }
        return result;
    }

    /**
     * 初始化userContext
     */
    private LantUser initUserContext() {
        // 先清除数据
        LantUserLocal.remove();
        LantUser user = null;
        String token = CookieUtils.getCookieValue(servletRequest, FieldConstant.getLantToken());
        if (ObjectUtils.notEmpty(token)) {
            LantResult result = lantUserService.getUserByToken(token);

            if (result.getStatus().equals(ResponseStatusEnum.BAD_REQUEST.getValue())) {
                logger.error(String.format("查询用户信息异常", result.getMsg()));
                return user;
            }

            user = (LantUser) result.getData();
        }

        if (ObjectUtils.notNull(user)) {
            // 填充数据
            LantUserLocal.set(user);
        }

        return user;
    }

}
